package net.zoneland.knowledge.aop;

import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 查询操作aop拦截器工具类.
 * @author zmq
 * 2021/10/21 14:51
 */
public final class SearchOperationAopUtils {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationAopUtils.class);

    /**
     * 私有构造.
     */
    private SearchOperationAopUtils() {

    }

    /**
     * 环绕通知.
     * @param joinPoint 方法执行体
     * @param stopWatchEnabled 是否开启监控
     * @return 返回结果
     * @throws Exception 异常
     */
    public static Object around(final ProceedingJoinPoint joinPoint, final boolean stopWatchEnabled) throws Exception {
        Object object = null;
        try {
            if (stopWatchEnabled) {
                final StopWatch sw = StopWatch.createStarted();
                // 执行源方法
                object = joinPoint.proceed();
                sw.split();
                LOGGER.info("==========stop watch, instanceClass:{}, searchDto:{}, consumerTime:{}",
                    joinPoint.getTarget().getClass().getCanonicalName(),
                    joinPoint.getArgs()[0].hashCode(),
                    sw.getSplitTime());
                sw.stop();
            } else {
                // 执行源方法
                object = joinPoint.proceed();
            }
        } catch (Throwable e) {
            LOGGER.error("ES查询业务执行异常", e);
            throw new Exception(e);
        }
        return object;
    }
}
